import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Form, Row, Col, Spin, Input, Select, Radio } from 'antd';
import AdModal from '@/components/AdModal';
import moment from 'moment';
import AntdForm from '@/components/AntdForm';
import AdSelect from '@/components/AdSelect';
import AntdFormItem from '@/components/AntdFormItem';
import AntdInput from '@/components/AntdInput';
import AntdDatePicker from '@/components/AntdDatePicker';
import EditPage from '@/components/EditPage';
import {
  queryDict,
  formItemFragement,
  filterAddFile,
  filterDeteteFile,
  formatPrice,
  queryFileList,
} from '@/utils/common';
import { allDictList } from '@/utils/constans';
import prompt from '@/components/Prompt';
import {
  selectArchivesDetailAndInfo,
  renderTableAdSelect,
  codes,
  allUrl,
  allDispatchType,
} from './utils';
import SearchSelect from '@/components/SearchSelect';
import FileReader from '@/components/FileReader';
import { columns1, supplierColumns } from '@/pages/Common/common';
import OilInfoBind from './OilInfoBind';
const dateFormat = 'YYYY-MM-DD';
const { TextArea } = Input;
const { Option } = Select;

@connect(({ Archives, component, loading }) => ({
  oilCardList: Archives.oilCardList,
  oilInfoDetails: Archives.oilInfoDetails,
  archivesDetail: Archives.archivesDetail,
  dictObject: component.dictObject,
  loading: loading.effects[allDispatchType.oilInfoList],
}))
@Form.create()
export default class ArchivesInfo extends Component {
  state = {
    selectedRows: [],
    bindSelectedRows: [],
    addType: 'add',
    fileList: [],
    activeKey: ['1', '2'],
    deleteFileIds: [],
    ownCompany: '',
    vehicleId: '',
    oilType: '',
    oilCardType: '',
    totalPrice: '',
    unitPrice: '',
    oilAmount: '',
    cars: [],
    oilTime: '',
    mileage: '',
    oilCardCus: '',
    oilCardNo: '',
    oilCardId: '',
  };
  fileList = [];

  componentWillMount() {
    const allDict = [allDictList.currencyType, allDictList.oilType, allDictList.saleCompany];
    queryDict({ props: this.props, allDict });
  }

  componentWillReceiveProps(nextProps, nextState) {
    const { oilInfoDetails, id, type, archivesId, archivesDetail } = nextProps;
    const { cars } = this.state;
    if (archivesDetail[archivesId] && archivesDetail[archivesId].vehicleId && cars.length == 0) {
      this.setState({
        cars: [{ id: archivesDetail[archivesId].vehicleId }],
        ownCompany: archivesDetail[archivesId].ownCompanyName,
      });
    }
    if (type === 'edit' && oilInfoDetails[id]) {
      this.setState({ cars: [{ id: oilInfoDetails[id].vehicleId }] });
    }
  }
  componentDidMount() {
    const { dispatch, id } = this.props;
    if (!id) return;
    this.getSelectDetails(id);
    this.queryFileList(id);
  }

  handleStateChange = (options = []) => {
    options.map(item => {
      this.setState(item);
    });
  };

  //详情信息：
  getSelectDetails = ID => {
    const { dispatch } = this.props;
    dispatch({
      type: allDispatchType.oilInfoDetails,
      payload: { id: ID },
      callback: data => {
        if (!data) return;
        const {
          totalFee,
          price,
          oilAmount,
          oilTime,
          mileage,
          oilSiteName,
          oilCardId,
          oilCardNo,
        } = data;
        const unitPrice = formatPrice(price);
        this.setState(
          {
            cars: [{ id: data.vehicleId }],
            totalPrice: totalFee,
            oilAmount,
            oilTime,
            mileage,
            oilCardId,
            oilCardNo,
          },
          () => {
            this.getOilCardList(oilSiteName, 'sellCompanyCode', { oilCardId, oilCardNo });
          }
        );
        this.props.form.setFieldsValue({ price: unitPrice });
      },
    });
  };

  queryFileList = id => {
    queryFileList({
      props: this.props,
      params: { bizId: id, fileBizType: 'OIL_MANA' },
      callback: data => {
        if (!data) return;
        this.fileList = data;
        this.props.form.setFieldsValue({ fileTokens: data });
      },
    });
  };

  handleOk = () => {
    const { form, type, oilInfoDetails, id, archivesId } = this.props;
    const {
      fileList,
      deleteFileIds,
      cars,
      oilCardId,
      oilCardNo,
      addType,
      bindSelectedRows,
    } = this.state;
    if (addType == 'bind') {
      if (bindSelectedRows.length == 0) {
        prompt({ content: '请选择记录', type: 'warn' });
        return;
      }
      const params = { archivesId: archivesId, ids: bindSelectedRows.map(v => v.id) };
      this.dispatchOperate(params);
    } else {
      form.validateFieldsAndScroll((err, values) => {
        if (err) {
          return;
        }
        const { addType, oilCard, oilTime, fileTokens, ...value } = values;
        value.archivesId = archivesId; //档案id

        //编辑时传入id
        if (id) {
          value.id = id;
          if (deleteFileIds.length > 0) {
            value.deleteFileIds = deleteFileIds;
          }
        }
        //图片：
        value.fileTokens = filterAddFile(fileTokens);
        value.deleteFileIds = filterDeteteFile(fileTokens, this.fileList);
        value.oilCardId = oilCardId;
        value.oilCardNo = oilCardNo;
       
        
        //时间：
        value.oilTime = oilTime ? moment(oilTime).format(dateFormat) : '';
        //保存车辆
        if (cars.length > 0) {
          const vehicleId = cars.map(v => {
            return v.id;
          });
          value.vehicleId = vehicleId.join(',');
        } else {
          value.vehicleId = '';
        }
        // console.log('oilCard--',value)
        
        // console.log('value', value);
        this.dispatchOperate(value, 1);
      });
    }
  };

  dispatchOperate = (params, flag) => {
    const { dispatch, oilInfoList } = this.props;
    dispatch({
      type: flag ? allDispatchType.oilInfoOperate : allDispatchType.oilBindInfoOperate,
      payload: params,
      callback: () => {
        oilInfoList();
        this.candleModal();
      },
    });
  };
  candleModal = () => {
    const { setOilInfoModal } = this.props;
    setOilInfoModal();
    this.handleStateChange([{ bindSelectedRows: [] }]);
  };

  //切换加油方式：
  onChangeType = (value, type) => {
    this.getOilCardList(value, type);
  };
  //油卡下拉数据
  getOilCardList = (value, type, oilCard) => {
    const {
      dispatch,
      form: { setFieldsValue, resetFields },
    } = this.props;
    if (!oilCard) {
      setFieldsValue({ oilCard: '' });
    } else {
    }
    this.setState(
      {
        [type]: value,
        oilCardId: oilCard ? oilCard.oilCardId : '',
        oilCardNo: oilCard ? oilCard.oilCardNo : '',
      },
      () => {
        if (type == 'oilType') return;
        const { oilSite, sellCompanyCode, cars } = this.state;
        console.log('car', cars)
        let vehicleId = '';
        if (cars && cars.length > 0) {
          vehicleId = cars.map(v => {
            return v.id;
          });
          vehicleId = vehicleId.join(',');
        }
        let params = {};
        params.pageSize = 1000;
        params.vehicleId = vehicleId;
        if (sellCompanyCode) {
          params.sellCompanyCode = sellCompanyCode;
        }
        console.log('vehicleId', vehicleId)
        if (vehicleId) {
          dispatch({
            type: allDispatchType.oilCardList,
            payload: params,
            callback: data => {
              this.setState({
                oilCardCus: true,
              });
            },
          });
        }
      }
    );
  };
  getValue = values => {
    this.setState(
      {
        cars: values,
        ownCompany: values[0].ownCompanyName,
      },
      () => {
        this.changeHundredConsump(values, 'cars'); //计算油耗
        this.getOilCardList(values, 'cars'); //获取油卡号
      }
    );
  };
  //计算总价
  onChangeNum = (value, type) => {
    if (type == 'oilAmount') this.changeHundredConsump(value, type);

    this.setState(
      {
        [type]: value,
      },
      () => {
        //单价 = 总价/加油量
        const { totalPrice, oilAmount } = this.state;
        let unitPrice = '';
        if (totalPrice && oilAmount) {
          unitPrice = (Number(totalPrice) / Number(oilAmount)).toFixed(2);
        }
        this.props.form.setFieldsValue({ price: unitPrice });
      }
    );
  };
  // 计算 本次油耗
  changeHundredConsump = (value, type) => {
    const {
      form: { getFieldsValue, setFieldsValue },
      dispatch,
      id,
    } = this.props;
    const { cars } = this.state;

    this.setState(
      {
        [type]: value,
      },
      () => {
        const { mileage, oilTime, oilAmount } = this.state;
        const _oilTime = oilTime ? moment(oilTime).format(dateFormat) : '';
        const param = { mileage, oilAmount, oilTime: _oilTime };
        let vehicleId = '';
        if (id) param.id = id;
        if (cars.length > 0) {
          vehicleId = cars[0].id;
        }
        param.vehicleId = vehicleId;
        console.log('param', param, '---', _oilTime, oilAmount, mileage, vehicleId);
        if (_oilTime && oilAmount && mileage && vehicleId) {
          dispatch({
            type: allDispatchType.calHundredConsump,
            payload: param,
            callback: data => {
              data && setFieldsValue({ avgHundredConsump: data });
            },
          });
        }
      }
    );
  };
  oilCardTypeSelectd = oilCardType => {
    this.setState({ oilCardType });
  };
  changeOilCard = val => {
    this.setState({
      oilCardId: val.split(',')[0],
      oilCardNo: val.split(',')[1],
    });
  };

  render() {
    const {
      form: { getFieldDecorator },
      type,
      dictObject,
      oilCardList,
      oilInfoDetails,
      visibleOperate,
      id,
      archivesId,
      loading,
      disabled,
      mode,
    } = this.props;

    const {
      selectedRows,
      addType,
      fileList,
      ownCompany,
      oilCardType,
      unitPrice,
      oilAmount,
      cars,
    } = this.state;
    const isDetail = mode == 'detail' ? true : false;
    const showFooter = isDetail ? { footer: null } : {};
    const detail = oilInfoDetails[id] || {};
    const _oilCardType = oilCardType ? oilCardType : detail.oilType || '';
    const editPageParams = {
      // title: detail.oilNo ? '编辑加油记录' : '新增加油记录',
      // headerOperate: this.headerOperate(),
      panelTitle: ['基础信息', '费用详情'],
    };
    const commonParams = {
      getFieldDecorator,
    };

    const prefixSelector = (
      <AntdFormItem code="currencyType" initialValue={detail.value || 'CNY'} {...commonParams}>
        <Select style={{ width: 120 }}>
          {dictObject[allDictList.currencyType] &&
            dictObject[allDictList.currencyType].map(item => (
              <Option key={item.code}>{item.value}</Option>
            ))}
        </Select>
      </AntdFormItem>
    );

    const formItem = [
      [
        <AntdFormItem
          label="单据号码"
          code="oilNo"
          initialValue={detail.oilNo || '保存后系统自动生成'}
          {...commonParams}
        >
          <AntdInput disabled={true} />
        </AntdFormItem>,
        <span></span>,
      ],
      [
        <AntdFormItem
          label="车牌号"
          // rules={[{ required: true }]}
          code="vehicleId"
          initialValue={detail.vehicleId}
          {...commonParams}
        >
          <SearchSelect
            dataUrl="tms/tms-oil/selectOilVehicle"
            url="tms/tms-oil/selectOilVehicleView_s" // selectedData只只有id时需要传url
            selectedData={cars} // 选中值
            multiple={false} // 是否多选
            showValue="cartPlateOneNo"
            searchName="cartPlate"
            columns={columns1} // 表格展示列
            onChange={values => this.getValue(values, 'cars')} // 获取选中值
            scrollX={480}
            id="tmsOil_2"
            disabled={true}
          />
        </AntdFormItem>,
        <AntdFormItem
          label="所属公司"
          code="ownCompanyName"
          initialValue={ownCompany ? ownCompany : detail && detail.ownCompanyName}
          {...commonParams}
        >
          <AntdInput disabled={true} />
        </AntdFormItem>,
      ],
    ];

    const formItemDetails = [
      [
        <AntdFormItem
          label="加油站名称"
          code="oilSiteName"
          initialValue={detail.oilSiteName}
          {...commonParams}
        >
          <AdSelect
            isExist={true}
            data={dictObject[allDictList.saleCompany]}
            payload={{ code: allDictList.saleCompany }}
            disabled={disabled}
            placeholder={isDetail ? '' : '请选择'}
            onChange={(value, option) => {
              this.getOilCardList(value, 'sellCompanyCode');
              this.setState({
                // oilSite: option.props.children,
              });
            }}
          />
        </AntdFormItem>,
        <AntdFormItem
          label="加油方式"
          code="oilType"
          initialValue={detail.oilType}
          rules={[{ required: true }]}
          {...commonParams}
        >
          <Select
            onSelect={this.oilCardTypeSelectd}
            onChange={(value, options) => this.onChangeType(value, 'oilType')}
            disabled={disabled}
          >
            {dictObject[allDictList.oilType] &&
              dictObject[allDictList.oilType].map(item => (
                <Option key={item.code}>{item.value}</Option>
              ))}
          </Select>
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="油卡号"
          code="oilCardNo"
          rules={[
            {
              required: _oilCardType === 'CARD'||_oilCardType === 'OIL-MONTHLYBALANCE' ? true : false,
              message: '请输入油卡号',
            },
          ]}
          initialValue={isDetail ? ' ' : detail.oilCardNo || undefined}
          {...commonParams}
        >
          <Select
            showSearch
            filterOption={(input, option) =>
              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
            style={{ width: '100%' }}
            allowClear={true}
            disabled={disabled}
            onChange={this.changeOilCard}
          // placeholder={isDetail ? '' : '请选择'}
          >
            <Option value="">请选择</Option>
            {oilCardList.list &&
              oilCardList.list.map((v, i) => {
                return (
                  <Option key={i} value={`${v.id},${v.cardNo}`}>
                    {v.cardNo}
                  </Option>
                );
              })}
          </Select>
        </AntdFormItem>,
        <AntdFormItem
          label="加油时间"
          code="oilTime"
          rules={[{ required: true }]}
          initialValue={detail && detail.oilTime ? moment(detail.oilTime, dateFormat) : null}
          {...commonParams}
        >
          <AntdDatePicker
            disabled={disabled}
            onChange={e => this.changeHundredConsump(e, 'oilTime')}
          />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="加油人"
          code="oilPerson"
          rules={[{ required: true }]}
          initialValue={detail.oilPerson}
          {...commonParams}
        >
          <AntdInput disabled={disabled} />
        </AntdFormItem>,
        <AntdFormItem
          label="当前里程(KM)"
          code="mileage"
          rules={[{ required: true }]}
          initialValue={detail.mileage || undefined}
          {...commonParams}
        >
          <AntdInput disabled={disabled} onChange={e => this.changeHundredConsump(e, 'mileage')} />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="加油量(升)"
          code="oilAmount"
          rules={[{ required: true }]}
          initialValue={detail.oilAmount}
          {...commonParams}
        >
          <AntdInput
            disabled={disabled}
            mode="money"
            label="加油量"
            placeholder="长度不超过18位可保留两位小数"
            onChange={e => this.onChangeNum(e, 'oilAmount')}
          />
        </AntdFormItem>,
        <AntdFormItem label="单价" code="price" getFieldDecorator={getFieldDecorator}>
          <AntdInput disabled={true} placeholder="" />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="总金额"
          code="totalFee"
          rules={[{ required: true, message: '请输入' }]}
          getFieldDecorator={getFieldDecorator}
          initialValue={formatPrice(detail.totalFee)}
        >
          <AntdInput
            mode="money"
            disabled={disabled}
            label="总金额"
            placeholder="长度不超过18位可保留两位小数"
            addonBefore={prefixSelector}
            onChange={e => this.onChangeNum(e, 'totalPrice')}
          />
        </AntdFormItem>,
        <AntdFormItem
          label="本次油耗"
          initialValue={detail.avgHundredConsump}
          code="avgHundredConsump"
          {...commonParams}
        >
          <AntdInput disabled={true} placeholder="" />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem label="备注" code="remarks" initialValue={detail.remarks} {...commonParams}>
          <AntdInput
            disabled={disabled}
            maxlen={200}
            type="textarea"
            placeholder={isDetail ? '' : '请输入不超过200字符'}
          />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem label="票据" code="fileTokens" initialValue={fileList} {...commonParams}>
          <FileReader urlType="tms" disabled={disabled} showUpload={isDetail ? false : true} />
        </AntdFormItem>,
      ],
    ];

    return (
      <Fragment>
        <AdModal
          visible={visibleOperate}
          title={mode == 'detail' ? '加油详情' : type == 'edit' ? '编辑加油记录' : '新增加油记录'}
          onOk={this.handleOk}
          okButtonProps={{ disabled }}
          onCancel={() => {
            this.candleModal();
          }}
          okText="保存"
          width="80%"
          bodyStyle={{
            height: 'calc(100vh - 130px)',
            overflowY: 'auto',
            padding: '10px 24px',
          }}
          {...showFooter}
        >
          {type == 'add' && (
            <AntdForm>
              <AntdFormItem label="类型" code="addType" initialValue={addType} {...commonParams}>
                <Radio.Group
                  onChange={e => {
                    this.handleStateChange([{ addType: e.target.value, bindSelectedRows: [] }]);
                  }}
                >
                  <Radio value="add" disabled={disabled}>
                    新增加油记录
                  </Radio>
                  <Radio value="bind" disabled={disabled}>
                    关联加油记录
                  </Radio>
                </Radio.Group>
              </AntdFormItem>
            </AntdForm>
          )}

          {addType == 'add' ? (
            <EditPage {...editPageParams}>
              <Spin spinning={false}>
                <AntdForm>{formItemFragement(formItem)}</AntdForm>
              </Spin>
              <Spin spinning={false}>
                <AntdForm>{formItemFragement(formItemDetails)}</AntdForm>
              </Spin>
            </EditPage>
          ) : (
              <OilInfoBind
                archivesId={archivesId}
                cars={this.state.cars}
                getBindRows={val => this.handleStateChange([{ bindSelectedRows: val }])}
              />
            )}
        </AdModal>
      </Fragment>
    );
  }
}
